package org.yaac.server.file;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.yaac.server.delegate.AsyncMemcacheServiceDelegate;
import org.yaac.server.util.AutoBeanUtil;
import org.yaac.server.util.FileUtil;
import org.yaac.shared.file.CacheUploadResult;
import org.yaac.shared.file.CacheUploadResult.Status;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 * 
 * upload a file into mem-cache for future use
 */
public class CacheUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final Logger logger;

	private final AsyncMemcacheServiceDelegate memcache;
	
	@Inject
	CacheUploadServlet(Logger logger, AsyncMemcacheServiceDelegate memcache) {
		super();
		this.logger = logger;
		this.memcache = memcache;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// Create a new file upload handler
		String resultStr = null;
		
		try {
			FileItemIterator i = new ServletFileUpload().getItemIterator(req);

			while (i.hasNext()) {
				FileItemStream item = i.next();
				InputStream stream = item.openStream();
				try {
					String randomId = UUID.randomUUID().toString();	// cache ID
					byte[] rawData = FileUtil.toByteArray(stream);	// cache data

					memcache.put(randomId, rawData);
					logger.info("Cached uploaded file id : " + randomId + " with size = " + rawData.length);
					
					CacheUploadResult result = AutoBeanUtil.newCacheUploadResult(Status.SUCCESS, randomId, item.getName(), rawData.length);
					resultStr = AutoBeanUtil.encode(CacheUploadResult.class, result);
				} finally {
					stream.close();
				}
			}
		} catch (FileUploadException e) {
			CacheUploadResult result = AutoBeanUtil.newCacheUploadResult(Status.FAIL, null, null, null);
			resultStr = AutoBeanUtil.encode(CacheUploadResult.class, result);
			
			logger.log(Level.SEVERE, "failed to upload file", e);
		}
		
		// make sure the plain json will be sent back
		resp.setContentType("text/html"); 
		resp.getWriter().print(resultStr);
	}
}